package juc.completablefuture;

import java.util.concurrent.*;

/**
 * @ClassName UseCompletableFuture
 * @PackageName completablefuture
 * @projectName myThread
 * @Description 
 * @Author games
 * @Date 2025/8/27 下午1:20
 * @Version 1.0
 */
public class TestFutureTask {
    public static void main(String[] args) throws Exception {
        FutureTask<String> ft1 = new FutureTask<>(new T1Task());
        FutureTask<String> ft2 = new FutureTask<>(new T2Task());
        FutureTask<String> ft3 = new FutureTask<>(new T3Task());
        FutureTask<String> ft4 = new FutureTask<>(new T4Task());
        FutureTask<String> ft5 = new FutureTask<>(new T5Task());

        ExecutorService executorService = Executors.newFixedThreadPool(5);
        executorService.submit(ft1);
        executorService.submit(ft2);
        executorService.submit(ft3);
        executorService.submit(ft4);
        executorService.submit(ft5);
        /**
         * 使用了 FutureTask.get() 方法，该方法会阻塞当前线程直到任务完成
         * 主线程按顺序调用 ft1.get()、ft2.get() 等，必须等待前一个任务完成后才能获取下一个任务结果
         * 虽然任务在提交时是并发执行的，但结果获取是串行的
         */
        System.out.println(ft2.get());
        System.out.println(ft3.get());
        System.out.println(ft4.get());
        System.out.println(ft5.get());
        System.out.println(ft1.get());
        executorService.shutdown();
    }

    static class T1Task implements Callable<String> {
        @Override
        public String call() throws Exception {
            System.out.println("T1 查询商品基本信息:" + Thread.currentThread().getName());
            TimeUnit.MILLISECONDS.sleep(5000);
            return "商品基本信息查询成功";
        }
    }

    static class T2Task implements Callable<String> {
        @Override
        public String call() throws Exception {
            System.out.println("T2 查询商品价格:" + Thread.currentThread().getName());
            TimeUnit.MILLISECONDS.sleep(50);
            return "商品价格查询成功";
        }
    }

    static class T3Task implements Callable<String> {
        @Override
        public String call() throws Exception {
            System.out.println("T3 查询商品库存:" + Thread.currentThread().getName());
            TimeUnit.MILLISECONDS.sleep(100);
            return "商品库存查询成功";
        }
    }

    static class T4Task implements Callable<String> {
        @Override
        public String call() throws Exception {
            System.out.println("T4 查询商品图片:" + Thread.currentThread().getName());
            TimeUnit.MILLISECONDS.sleep(100);
            return "商品图片查询成功";
        }

    }

    static class T5Task implements Callable<String> {
        @Override
        public String call() throws Exception {
            System.out.println("T5 查询商品销售状态:" + Thread.currentThread().getName());
            TimeUnit.MILLISECONDS.sleep(100);
            return "商品销售状态查询成功";
        }
    }

}
